// 是否为生产环境
const environment = process.env.VUE_APP_DEV === 'production';

// 引入编译进度条
const chalk = require('chalk');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
// 可视化查看chunk-vendors.js这个文件里面地内容
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// 清除console.log打印
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// 开启gzip压缩
const CompressionWebpackPlugin = require("compression-webpack-plugin");

// cdn 外部扩展，通过 cdn 引入，不会被webpack打包
const cdn = {
  // cdn的css链接
  css: [
    // 'https://cdn.jsdelivr.net/npm/ant-design-vue@1.7.8/dist/antd.min.css',
    // "//unpkg.com/element-ui@2.10.1/lib/theme-chalk/index.css",
    // videojs
    "//unpkg.com/video.js@7.10.2/dist/video-js.min.css",
  ],
  // cdn的js链接
  js: [
    // 必须放在第一位,不然会报错
    "//unpkg.com/vue@2.6.10/dist/vue.min.js",
    "//unpkg.com/vue-router@3.0.6/dist/vue-router.min.js",
    "//unpkg.com/vuex@3.1.1/dist/vuex.min.js",
    "//unpkg.com/axios@0.19.0/dist/axios.min.js",
    // 'https://cdn.jsdelivr.net/npm/ant-design-vue@1.7.8/dist/antd.min.js',
    // "//unpkg.com/element-ui@2.10.1/lib/index.js",
    // lazyload
    // "//unpkg.com/vue-lazyload/vue-lazyload.js",
    // videojs
    "//unpkg.com/video.js@7.10.2/dist/video.min.js"
  ]
}


module.exports = {
  // 配置打包后的文件的路径
  publicPath: './',
  // 打包后文件名
  // outputDir: 'myDist',
  // 静态资源打包名
  assetsDir: 'static',
  // 关闭eslint
  lintOnSave: false,
  // 是否开启sourcemap,设置为false时可加速生产环境构建
  productionSourceMap: !environment,
  parallel: require("os").cpus().length > 1,
  // 文件名哈希
  filenameHashing: true,
  // 服务器代理,解决跨域
  devServer: {
    port: 8080,
    open: true,
    proxy: {
      '/api/': {
        target: process.env.VUE_APP_API,
        // 支持跨域
        changeOrigin: true,
        // pathRewrite: {
        //   '^/api': ''
        // },
      },
      '/v1/': {
        target: 'http://localhost:3000',
        // 支持跨域
        changeOrigin: true,
        // pathRewrite: {
        //   '^/api': ''
        // },
      }
    },
    // 开启热更新
    hotOnly: true
  },
  configureWebpack: config => {
    // config.resolve.symlinks(true); // 修复热更新失效
    // 生产环境需要
    if (environment) {
      config.plugins.push(
        // 分析打包
        new BundleAnalyzerPlugin(),

        // config.plugin('speed')
        //   .use(SpeedMeasureWebpackPlugin),
      
        // 打包进度条
        new ProgressBarPlugin({
          format: `  :msg [:bar] ${chalk.green.bold(
            ':percent'
          )} (:elapsed s)`,
        }),

        // 开启gzip
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
          threshold: 10240,
          minRatio: 0.8
        })
      )
      // 配置需要cdn的包
      config.externals = {
        vue: 'Vue',
        'vue-router': 'VueRouter',
        axios: 'axios',
        vuex: 'Vuex',
        videojs: 'Videojs'
        // "element-ui": "ELEMENT",
        // 'ant-design-vue': 'antd',
        // 'vue-lazyload': 'VueLazyload',
      }
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            vendor: {
              chunks: 'all',
              test: /[\\/]node_modules[\\/]/,
              name: 'app-chunk-vendors',
              minChunks: 1,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 100
            },
            common: {
              chunks: 'all',
              test: /[\\/]src[\\/]js[\\/]/,
              name: 'common',
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 60
            },
            styles: {
              name: 'styles',
              test: /\.(sa|sc|c)ss$/,
              chunks: 'all',
              enforce: true
            },
            runtimeChunk: {
              name: 'manifest'
            }
          }
        },
        minimizer: [
          // 清除console.log打印和注释
          new UglifyJsPlugin({
            uglifyOptions: {
              output: {
                comments: false, // 去掉注释
              },
              warnings: false,
              compress: {
                drop_console: true,
                drop_debugger: true,
                pure_funcs: ['console.log'] //移除console
              },
              sourceMap: false,
              parallel: true
            }
          }),
        ]
      }
    }
  },
  // chainWebpack通过 webpack-chain 维护的，修改一些高级配置
  // 比如修改，添加，替换loader, 使用、修改插件
  chainWebpack: config => {
    if (environment) {
      // 图片压缩处理
      const imgRule = config.module.rule('images')
      imgRule
        .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({ bypassOnDebug: true })
        .end()
    }
    // webpack 会默认给commonChunk打进chunk-vendors，所以需要对webpack的配置进行delete
    // config.optimization.delete('splitChunks');
    /**
     * 添加CDN参数到htmlWebpackPlugin配置中
     */
    config.when(process.env.VUE_APP_DEV === 'production', config => {
    /* 设置打包入口 */
    // config.entry('app').clear().add('./src/main-prod.js')
      config.plugin('html').tap(args => {
        // html中添加cdn
        args[0].cdn = cdn;
        return args;
      })
    });
    config.when(process.env.VUE_APP_DEV === 'development', config => {
      // config.entry('app').clear().add('./src/main.js')
      config.plugin('html').tap(args => {
        //添加参数isProd
        args[0].cdn = [];
        return args;
      })
    });
  },
  // antd按需引入后,less-loader版本过高无法编译,需要加上这段代码
  css: {
    sourceMap: false,
    loaderOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  }
}